package com.laoli.lab39;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * exceptionally()示例：捕获异常并返回默认值
 */
public class ExceptionallyDemo {
    public static void main(String[] args) throws InterruptedException {
        // 问：任务A、任务B各出一个随机数(1-10)，任务C输出这两个随机数的和？

        // 异步任务A
        CompletableFuture<Integer> taskA = CompletableFuture.supplyAsync(() -> {
            Integer rndA = new Random().nextInt(10) + 1;
            System.out.println("rndA = " + rndA);
            return rndA;
            //throw new RuntimeException("taskAException");
        });
        // 异步任务B
        CompletableFuture<Integer> taskB = CompletableFuture.supplyAsync(() -> {
            Integer rndB = new Random().nextInt(10) + 1;
            System.out.println("rndB = " + rndB);
            return rndB;
            //throw new RuntimeException("taskBException");
        });

        // 异步任务C
        CompletableFuture<Void> taskC = CompletableFuture.allOf(taskA, taskB);
        // 聚合结果
        taskC.thenApply(result -> taskA.join() + taskB.join())
                .exceptionally(exception->{
                    System.out.printf("【exceptionally】发生异常：%s\n", exception.getCause().getMessage());
                    return 0; // 必须是 Integer 类型
                })
                // 输出结果
                .thenAccept(result -> System.out.println("result = " + result)); // 0

        // 主线程休眠
        Thread.sleep(100);
    }
}
